package com.example.jsr_study.config;

import com.example.jsr_study.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

/**
 * 配置全局异常管理
 *
 * @author Journey
 * @version 创建时间：2020年2月3日 下午3:45:53
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = {MethodArgumentNotValidException.class, BindException.class})
    public Object methodArgumentNotValidException(Exception exception) {
        BindingResult bindingResult = null;
        if (exception instanceof MethodArgumentNotValidException) {
            bindingResult = ((MethodArgumentNotValidException) exception).getBindingResult();
        } else if (exception instanceof BindException) {
            bindingResult = ((BindException) exception).getBindingResult();
        }
        String defaultMessage = null == bindingResult ? "" : bindingResult.getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .filter(Strings::isNotBlank)
                .sorted()
                .collect(Collectors.joining(","));
        return Result.fail(defaultMessage);
    }

}